//
//  AccountingBook.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import Foundation
import GRDB
import SwiftUI

struct AccountingBook :RecordSyncable, Codable, Identifiable, Equatable, Hashable, FetchableRecord, MutablePersistableRecord {
    var id:Int64?
    var bookId:String?
    var bookName:String?
    var bookColor:String?
    var bookRemark:String?
    var bookCover:String?
    var uid:String?
    var createTime:String?
    var updateTime:String?
    var orderId:Int = 0
    var isArchive:Int = 0
    var isDel:Int = 0
    var dataFlag:Int? = 0
    var sv:Int = 0
    
    static func == (lhs:AccountingBook, rhs:AccountingBook) -> Bool {
        return lhs.bookId == rhs.bookId
    }
    
    enum CodingKeys: String, CodingKey {
        case id, bookId = "book_id", bookName = "book_name", bookColor = "book_color", bookRemark = "book_remark", bookCover = "book_cover", uid, createTime = "creat_time", updateTime = "update_time", orderId = "order_id", isArchive = "is_archive", isDel = "is_del", dataFlag = "date_flag", sv
    }
    
    // 定义数据库表
    static let databaseTableName = "accounting_book"
    
    static let def_book_id = "koi_b_def001"
    
    enum Columns: String, ColumnExpression {
        case id, bookId = "book_id", bookName = "book_name", bookColor = "book_color", bookRemark = "book_remark", bookCover = "book_cover", uid, createTime = "creat_time", updateTime = "update_time", orderId = "order_id", isArchive = "is_archive", isDel = "is_del", dataFlag = "date_flag", sv
    }
    
    // 实现数据库持久化方法
    mutating func didInsert(with rowID: Int64, for column: String?) {
        id = rowID
    }
    
    mutating func makeUpdate() {
        self.dataFlag = DataFlag.update.rawValue
        updateTime = Date().toISODateString()
    }
    
    mutating func makeDelete() {
        self.dataFlag = DataFlag.delete.rawValue
        self.isDel = 1
        updateTime = Date().toISODateString()
    }
    
    mutating func archive() {
        self.isArchive = 1
        makeUpdate()
    }
    
    mutating func unArchive() {
        self.isArchive = 0
        makeUpdate()
    }
    
    static func createTable(dbQueue: DatabaseQueue) {
        do {
            try dbQueue.write{ db in
                if (try db.tableExists(databaseTableName)) {
                    logger.info("table already exists \(databaseTableName)")
                } else {
                    try db.create(table: databaseTableName) { t in
                        t.autoIncrementedPrimaryKey(Columns.id.rawValue)
                        t.column(Columns.bookId.rawValue, .text)
                        t.column(Columns.bookName.rawValue, .text)
                        t.column(Columns.bookColor.rawValue, .text)
                        t.column(Columns.bookRemark.rawValue, .text)
                        t.column(Columns.bookCover.rawValue, .text)
                        t.column(Columns.uid.rawValue, .text)
                        t.column(Columns.createTime.rawValue, .text)
                        t.column(Columns.updateTime.rawValue, .text)
                        t.column(Columns.orderId.rawValue, .integer)
                        t.column(Columns.isArchive.rawValue, .integer)
                        t.column(Columns.isDel.rawValue, .integer)
                        t.column(Columns.dataFlag.rawValue, .integer)
                        t.column(Columns.sv.rawValue, .integer)
                    }
                    try db.execute(sql: "CREATE UNIQUE INDEX unique_index_book_id_uid ON accounting_book (book_id, uid)")
                }
            }
        } catch {
            logger.error("create accounting_book table fail \(error)")
        }
    }
    
    func isDefaultBook() -> Bool {
        return bookId == AccountingBook.def_book_id
    }
    
    func getBookColor() -> Color {
        if (bookColor != nil && bookColor?.isEmpty == false) {
            return Color(hex: bookColor!)
        } else {
            return Color.koiColorPrimary
        }
    }
}
